package com.wujilee.wujileenetty.netty.netty.decoder.message;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

/**
 * @author liwuji
 * @date 2024/8/27
 * @desc
 **/
public class MsgPackClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4) );
                ch.pipeline().addLast("msgpack decoder", new MsgPackDecoder());
                // 该类在消息前增加4个字节记录消息长度
                ch.pipeline().addLast(new LengthFieldPrepender(4));
                ch.pipeline().addLast("msgpack encoder", new MsgpackEncode());
                ch.pipeline().addLast("hello",new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        System.out.println("连接建立成功");
                        ctx.writeAndFlush("hello server!");
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf byteBuf = (ByteBuf) msg;
                        byte[] bytes = new byte[byteBuf.readableBytes()];
                        System.out.println("接收到来自服务端的消息: " + new String(bytes, "utf-8"));
                    }
                });
            }
        });

        ChannelFuture sync = bootstrap.connect("127.0.0.1", 8080).sync();
        ChannelFuture sync1 = sync.channel().closeFuture().sync();

    }
}
